package com.erp.utils;

import redis.clients.jedis.Jedis;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class OrderNumberGenerator {

    private static final String REDIS_KEY = "order_number_counter";
    private static final String REDIS_HOST = "localhost";
    private static final int REDIS_PORT = 6379;
    private static final DateTimeFormatter DATE_TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    /**
     * 生成格式化订单号（线程安全）
     * @return 格式如 ORDER2023051514300000001
     */
    public static synchronized String generateOrderNumber() {
        try (Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT)) {
            // 生成递增序号（Redis 原子操作）
            Long nextOrderNumber = jedis.incr(REDIS_KEY);

            // 格式：ORDER + 年月日时分秒 + 7位序号（不足补零）
            return String.format("ORDER%s%07d",
                    DATE_TIME_FORMATTER.format(LocalDateTime.now()),
                    nextOrderNumber);
        }
    }

    /**
     * 初始化 Redis 计数器（可选）
     */
    public static void initRedisCounter(long initialValue) {
        try (Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT)) {
            jedis.setnx(REDIS_KEY, String.valueOf(initialValue));
        }
    }
}
